#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->boyBox->setProperty("isBoy", true);
    ui->girlBox->setProperty("isBoy", false);

    boy = new QPerson("小明");
    boy->setAge(20);
    boy->setProperty("socre", 60);
    boy->setProperty("sex", "boy");

    girl = new QPerson("小花");
    girl->setAge(25);
    girl->setProperty("socre", 80);
    girl->setProperty("sex", "girl");

    connect(ui->boyBox, &QSpinBox::valueChanged, this, [&](int value) {
        boy->setAge(value);
    });
    connect(ui->girlBox, &QSpinBox::valueChanged, this, [&](int value) {
        girl->setAge(value);
    });
    connect(boy, &QPerson::ageChanged, this, [&](unsigned value) {
        Q_UNUSED(value); // 如果不使用，这个宏可以消除警告
        ui->boyBox->setValue(value);
        QPerson *aPersion = qobject_cast<QPerson *>(sender());
        updateText(aPersion);
    });
    connect(girl, &QPerson::ageChanged, this, [&](unsigned value) {
        Q_UNUSED(value);
        ui->girlBox->setValue(value);
        QPerson *aPersion = qobject_cast<QPerson *>(sender());
        updateText(aPersion);
    });
}

void Widget::updateText(QPerson *aPersion)
{
    QString name = aPersion->property("name").toString();
    QString sex = aPersion->property("sex").toString();
    int socre = aPersion->property("socre").toInt();
    unsigned age = aPersion->age();

    ui->textEdit->appendPlainText(name+"，"+sex+QString::asprintf("，年龄 = %d，分数 = %d", age, socre));
}


Widget::~Widget()
{
    delete ui;
}


void Widget::on_boyBtn_clicked()
{
    boy->incAge();
}


void Widget::on_girlBtn_clicked()
{
    girl->incAge();
}


void Widget::on_clearBtn_clicked()
{
    ui->textEdit->clear();
}


void Widget::on_classBtn_clicked()
{
    const QMetaObject *meta = girl->metaObject();
    ui->textEdit->clear();
    ui->textEdit->appendPlainText("===元对象信息===\n");
    ui->textEdit->appendPlainText(QString("类命名：%1\n").arg(meta->className()));
    ui->textEdit->appendPlainText("---property---");
    for (int i=meta->propertyOffset(); i<meta->propertyCount(); i++) {
        QMetaProperty proper = meta->property(i);
        const char * properName = proper.name();
        QString properValue = boy->property(properName).toString();
        ui->textEdit->appendPlainText(QString("属性名称：%1，属性值：%2").arg(properName, properValue));
    }
    ui->textEdit->appendPlainText("");
    ui->textEdit->appendPlainText("---classInfo---");
    for (int i=meta->classInfoOffset(); i<meta->classInfoCount(); i++) {
        QMetaClassInfo classInfo = meta->classInfo(i);
        ui->textEdit->appendPlainText(QString("Name：%1，Value：%2").arg(classInfo.name(), classInfo.value()));
    }
}

